# -*- coding: utf-8 -*-
from odoo.exceptions import ValidationError
import base64
import urllib2
from odoo import models, fields, api
import json
import os
from odoo.http import request
import requests
import logging
from datetime import timedelta
from datetime import datetime
_logger = logging.getLogger(__name__)


class wechatUser(models.Model):
    _name = "wechat_mall.user"
    _description = u'微信客户'

    name = fields.Char('昵称')
    open_id = fields.Char('OpenId', required=True)
    union_id = fields.Char('UnionId')
    gender = fields.Integer('gender')
    language = fields.Char('语言')
    # register_type = fields.Selection(defs.WechatUserRegisterType.attrs.items(), string='注册来源',
    #  default=defs.WechatUserRegisterType.app)
    phone = fields.Char('手机号码')
    country = fields.Char('国家')
    province = fields.Char('省份')
    city = fields.Char('城市')
    avatar = fields.Html('头像', compute='_compute_avatar')
    avatar_url = fields.Char('头像链接')
    register_ip = fields.Char('注册IP')
    last_login = fields.Datetime('登陆时间')
    ip = fields.Char('登陆IP')
    # status = fields.Selection(defs.WechatUserStatus.attrs.items(), string='状态',
    #   default=defs.WechatUserStatus.default)

    # address_ids = fields.One2many('wechat_mall.address', 'wechat_user_id', string='收货地址')
    # order_ids = fields.One2many('wechat_mall.order', 'wechat_user_id', string='订单')

    @api.multi
    @api.depends('avatar_url')
    def _compute_avatar(self):
        for each_record in self:
            if each_record.avatar_url:
                each_record.avatar = """
                <img src="{avatar_url}" style="max-width:100px;">
                """.format(avatar_url=each_record.avatar_url)
            else:
                each_record.avatar = False

class wechat_partner(models.Model):
    _inherit = "res.partner"

    commission = fields.Float(u'佣金总额')
    withdraw = fields.Float(u'已提现')
    wechat_id = fields.Many2one("wechat_mall.user", u'微信信息')
    other_id = fields.Many2one("res.partner", u'上级ID')
    fenxiao = fields.Many2one("res.partner", u'所属企业分销商')
    stock_no = fields.Integer(u'虚拟库存')
    virtual_moving = fields.One2many("fenxiao.stock", 'user', string=u'库存移动')

    @api.multi
    def button_virtual_move(self):
        _logger.info(self.id)
        return {
            'name': u'库存移动',
            'view_type': 'form',
            'view_mode': 'tree,form',
            'res_model': 'fenxiao.stock',
            'view_id': False,
            'type': 'ir.actions.act_window',
            'domain': [('user', '=', self.id)],
        }

class fenxiao_stock(models.Model):
    _name = "fenxiao.stock"
    _description = u'分销商库存'

    user = fields.Many2one('res.partner', string=u"企业分销商",
                           required=True, domain=[('other_id', '=', False)])
    move_no = fields.Integer(u'移动库存数')
    date = fields.Date(u'移动时间')
    state = fields.Selection([
        ('draft', u'草稿'),
        ('done', u'完成')
    ], u'状态', default='draft')

    @api.one
    def confirm_move(self):
        self.state = 'done'
        partner = self.env['res.partner'].search([('id', '=', self.user.id)])
        partner[0]
        partner.stock_no += self.move_no

class money_recond(models.Model):
    _name = 'money.recond'

    user = fields.Many2one('res.partner', string=u'用户', readonly=True)
    sum = fields.Char(string=u'金额', readonly=True)
    data = fields.Datetime(string=u'日期', readonly=True)

class fenxiao_user(models.Model):
    _inherit = "res.users"

    fen_level = fields.Selection([
        ('1', u'一级'),
        ('2', u'二级'),
        ('3', u'三级')
    ], u'分销商层级', default='1')
    chengxu = fields.Binary(u'图片', attachment=True)
    wenjian = fields.Binary(u'下载')

    def get_wxCode_token(self):
        try:
            Param = self.env()['ir.config_parameter']
            app_id = Param.get_param('app_id')
            secret = Param.get_param('secret')
            if app_id and secret:
                url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=' + 'client_credential' + '&appid=' + app_id + '&secret=' + secret
                res = requests.get(url).text
                res = json.loads(res)
                _logger.info(res)
                access_token = res["access_token"]
                return access_token
            else:
                return False
        except Exception as e:
            print(e)
            return False

    def get_wxCode(self):
        test = self.get_wxCode_token()
        _logger.info(test)
        _logger.info(type(test))
        if test:
            textmod = {"scene": str(self.partner_id.id), "page": "pages/index/index",
                    "width": 130, "auto_color": True, "is_hyaline": False}
            # textmod = {
            #     "path":"pages/index/index?clientId=3","width": 130
            # }
            textmod = json.dumps(textmod).encode(encoding='utf-8')
            header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                        "Content-Type": "application/json"}
            url = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + test
            # url = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' + test

            req = urllib2.Request(url = url, data=textmod,headers=header_dict)
            res = urllib2.urlopen(req)
            res = res.read()
            b64str = base64.b64encode(res)
            self.write({
                'chengxu':b64str,
                'wenjian':b64str
            })
        else:
            raise ValidationError('请配置微信appid和secret!')
